<template>
  <a-row type="flex" justify="center" align="middle" style="min-height: 100vh">
    <a-col span="8">
      <a-form :model="formState" name="basic" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" autocomplete="off"
        @finish="onFinish" @finishFailed="onFinishFailed" :rules="loginRules">
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="formState.username" />
        </a-form-item>

        <a-form-item label="密码" name="password">
          <a-input-password v-model:value="formState.password" />
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
          <a-button type="primary" html-type="submit">登录</a-button> <router-link :to="'/register'">注册</router-link>
        </a-form-item>
        
      </a-form>
     
    </a-col>
  </a-row>
</template>
<script lang="ts" setup>
import { reactive } from 'vue';
import { loginRules } from "@/form-rules/login";
import { useRouter } from 'vue-router';
import { useStore } from '@/store';
import { message } from 'ant-design-vue';
import type { StateAll } from '@/store';
import http from '@/utils/http';

const store = useStore();
const router = useRouter();

interface FormState {
  username: string;
  password: string;
}

const formState = reactive<FormState>({
  username: '',
  password: ''
});
const onFinish = (values: any) => {
  //console.log(values)
  http.post('/authorize/token', values).then((res) => {
    if (res.data.status === "success") {
      //console.log(res.data.businessData)
      //设置相关变量到vuex
      store.commit('users/updateToken', res.data.businessData.token);
      store.commit('users/updateRefreshToken', res.data.businessData.refreshToken);
      store.commit('users/updateUserInfo', res.data.businessData.user);
      store.commit('users/updatePermission', res.data.businessData.permissionSet);
      //跳转到首页
      router.push("/");
      //定时向后端拉取token，时间间隔与后端设置的token过期时间相同
      const tokenInterval = setInterval(function () {
        const canRefresh = (store.state as StateAll).users.canRefresh;
        //从vuex中获取是否能拉取token的变量
        if (canRefresh) {
          const refreshToken = (store.state as StateAll).users.refreshToken;
          const token = (store.state as StateAll).users.token;
          // 刷新 token
          http.post('/authorize/refreshToken', null, {
            headers: {
              Authorization: "Bearer " + token,
            },
            params: {
              refreshToken: refreshToken
            },
          }).then((res) => {
            //重新设置token
            store.commit('users/updateToken', res.data.businessData);
          }).finally(() => {
            //将vuex中是否能拉取token的变量置为false,如果有请求，则置为true，在utils中的http.ts中设置
            store.commit('users/updateCanRefresh', false);
          });
        } else {
          //如果没有向后端发送请求，则不再刷新token
            clearInterval(tokenInterval);
        }
     //时间与后端token失效时间相同
      }, 300000);
    }
    else {
      message.error(res.data.businessData.errMsg);
    }
  })
};

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo);
};

</script>

